package com.apimanage.auth.service.impl;

import com.apimanage.auth.entity.User;
import com.apimanage.auth.model.dto.UserInfoDTO;
import com.apimanage.auth.service.AuthInternalService;
import com.apimanage.common.utils.JwtTokenUtil;
import com.apimanage.common.dto.UserDTO;
import com.apimanage.common.exception.ApiException;
import com.apimanage.common.service.UserCenterService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 认证内部服务实现类
 * 实现内部使用的认证服务功能
 * 
 * @author API管理平台
 */
@Service
@DubboService
public class AuthInternalServiceImpl implements AuthInternalService {

    // 注入UserCenterService服务（通过Dubbo引用）
    // 设置check=false，避免因为user-center服务不可用而导致auth-center启动失败
    @DubboReference(check = false, timeout = 3000)
    private UserCenterService userService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Value("${jwt.expire}")
    private Long expire;

    // 使用静态方法调用统一的JWT工具类，无需注入

    @Autowired
    private PasswordEncoder passwordEncoder;

    // Redis中存储黑名单token的前缀
    private static final String REDIS_KEY_PREFIX = "auth:blacklist:";

    /**
     * UserDTO转User
     */
    private User convertToEntity(UserDTO userDTO) {
        if (userDTO == null) {
            return null;
        }
        User user = new User();
        // 只复制相同的属性
        user.setId(userDTO.getId());
        user.setUsername(userDTO.getUsername());
        user.setEmail(userDTO.getEmail());
        user.setPhone(userDTO.getPhone());
        user.setStatus(userDTO.getStatus());
        return user;
    }

    /**
     * 校验令牌
     */
    private boolean validateToken(String token) {
        if (token == null) {
            return false;
        }

        // 检查token是否在黑名单中
        if (redisTemplate.hasKey(REDIS_KEY_PREFIX + token)) {
            return false;
        }

        // 使用JWT工具类验证token
        return JwtTokenUtil.validateToken(token);
    }

    
    @Override
    public UserInfoDTO getUserInfoByToken(String token) {
        if (!JwtTokenUtil.validateToken(token)) {
            throw new ApiException(401, "token无效或已过期");
        }

        try {
            // 使用JWT工具类获取用户信息
            UserDTO userDTO = JwtTokenUtil.getUserInfoFromToken(token);
            if (userDTO != null) {
                // 通过user-center服务获取完整用户信息
                UserDTO userFromService = userService.getUserByUsername(userDTO.getUsername());
                if (userFromService != null) {
                    User user = convertToEntity(userFromService);
                    UserInfoDTO userInfoDTO = new UserInfoDTO();
                    userInfoDTO.setUsername(user.getUsername());
                    userInfoDTO.setEmail(user.getEmail());
                    userInfoDTO.setPhone(user.getPhone());
                    // 取第一个角色作为主要角色
                    if (userDTO.getRoles() != null && !userDTO.getRoles().isEmpty()) {
                        userInfoDTO.setRole(userDTO.getRoles().get(0));
                    }
                    return userInfoDTO;
                }
            }
            throw new ApiException(401, "用户信息不存在");
        } catch (Exception e) {
            throw new ApiException(401, "获取用户信息失败");
        }
    }
    
    @Override
    public String refreshToken(String oldToken) {
        // 检查oldToken是否有效
        if (!validateToken(oldToken)) {
            throw new ApiException(401, "刷新token无效或已过期");
        }

        try {
            // 从token中获取用户信息
            UserDTO userDTO = JwtTokenUtil.getUserInfoFromToken(oldToken);
            if (userDTO != null) {
                // 生成新的token
                return JwtTokenUtil.generateToken(userDTO);
            }
            throw new ApiException(401, "刷新token失败");
        } catch (Exception e) {
            throw new ApiException(401, "刷新token失败");
        }
    }
    
    @Override
    public UserInfoDTO getUserInfo(Long userId) {
        try {
            // 通过user-center服务获取用户信息
            UserDTO userFromService = userService.getUserById(userId);
            if (userFromService != null) {
                User user = convertToEntity(userFromService);
                UserInfoDTO userInfoDTO = new UserInfoDTO();
                userInfoDTO.setUsername(user.getUsername());
                userInfoDTO.setEmail(user.getEmail());
                userInfoDTO.setPhone(user.getPhone());
                return userInfoDTO;
            }
            throw new ApiException(404, "用户不存在");
        } catch (Exception e) {
            throw new ApiException(500, "获取用户信息失败");
        }
    }
}